package com.mzj.saas.mservice.lock.Repository;

import com.mzj.saas.mservice.lock.entity.SmartLock;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface SmartLockRepository extends PagingAndSortingRepository<SmartLock, Long>, JpaSpecificationExecutor<SmartLock> {

    List<SmartLock> findBySnIn(List<String> sns);

    List<SmartLock> findByIdIn(List<Long> ids);

    SmartLock findBySn(String sn);

    SmartLock findByMatchUserId(String matchUserId);

    List<SmartLock> findByHouseId(String houseId);

    List<SmartLock> findByHouseIdAndStatus(String houseId,Integer status);

    List<SmartLock> findByHouseIdOrMac(String houseId, String mac);

    SmartLock findByMac(String mac);

    @Query("from SmartLock where sn = ?1 and mechineStatus=?2")
    SmartLock findBySnAndMechineStatus(String sn, Integer mechineStatus);

    @Modifying
    @Query(value = "UPDATE saas_smart_lock SET mechine_status = ?2 WHERE id = ?1", nativeQuery = true)
    int updateMechineStatusById(Long id, Integer mechineStatus);

    @Query(value = "SELECT l.id AS lockId FROM `saas_smart_lock` l LEFT JOIN `saas_house` h ON l.`house_id` = h.id WHERE h.id = ?1", nativeQuery = true)
    Long findByHouseIds(String houseId);

    List<SmartLock> findByOperatorId(String operatorId);

    void deleteByHouseId(String houseId);

    @Query(value = "select brand_id from saas_smart_lock WHERE id in(select lock_id from saas_smart_lock_auth WHERE house_id  = ?1)",nativeQuery = true)
    String lockType(String id);

    @Transactional
    @Modifying
    @Query(value = "UPDATE saas_smart_lock set electric_quantity=?1 where mac=?2", nativeQuery = true)
    int updateElectricQuantity(Integer mechineStatus, String mac);

    @Query(value = "select * from saas_smart_lock  where mac=?1",nativeQuery = true)
    SmartLock getSmartLock(String mac);

    @Query(value = "SELECT * FROM `saas_smart_lock` where house_id = ?1 and brand_id in (5,6)", nativeQuery = true)
    SmartLock findByHouseIdAnAndBrandIdIsFaceLock(String houseId);

    @Query(value = "SELECT * FROM `saas_smart_lock` where house_id = ?1", nativeQuery = true)
   SmartLock findByHouseIdAnAndBrandId(String houseId);

    List<SmartLock> findByOrgId(Long id);
}
